<?php
namespace app\portal\controller;
use cmf\controller\HomeBaseController;
use Hooklife\ThinkphpWechat\Wechat;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use think\Db;
use think\Log;

class WuyeController extends HomeBaseController{
    public function _empty($name){
        return $this->fetch($name);
    }

    public function token(){
        $data = input();
        //  Log::notice('`````````````微信token认证``````````````');
        //   Log::notice($data);
        if(isset($data['echostr'])){
            echo $data['echostr'];
        }
    }
    
    public function code(){
        $app_id = input('app_id');
        if(!empty($app_id)){
            $res = Db::name('wx_info')->where('app_id',$app_id)->field('user_id')->find();
            cookie('user_id',$res['user_id']);
        }
        $url = input('url');
        cookie('app_id',$app_id,7200);
        cookie('url',$url,7200);
        session('app_id',$app_id);
        $CodeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$app_id."&redirect_uri=http://".$_SERVER['HTTP_HOST']."/portal/wuye/codenext.html&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
        return view('',[
            'CodeUrl' => $CodeUrl
        ]);
    }
    public function codenext(){
        $code = $this->request->param('code');
        $app_id = cookie('app_id');
        $user_id = cookie('user_id');
        if(!empty($app_id)){
            $app_id = session('app_id');
            $res = Db::name('wx_info')->where('app_id',$app_id)->field('app_secret')->find();
            $secret = $res['app_secret'];
        }

        if(!empty($app_id) && !empty($secret) && !empty($code)){
            $url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$app_id.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code ';
            $weixin =  file_get_contents($url);
            $jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
            $array = get_object_vars($jsondecode);//转换成数组
            $openid = '';
        }

        if(isset($array['openid'])){
            cookie('openid',$array['openid']);
            $url = cookie('url');
            $userInfo = Db::name('wx_fans')->where('openid',$array['openid'])->find();
            $this->redirect($url);
//            if(empty($userInfo['phone'])){
//                $this->redirect("phone",[
//                    'url' => $url
//                ]);
//            }else{
//                $this->redirect($url);
//            }
        }
    }
    public function getPhone(){
        $data['phone'] = input('phone');
        $url = input('url');
        $openid = cookie('openid');
        if(!empty($openid)){
            $phone = Db::name('wx_fans')->where('phone',$data['phone'])->find();
            if($phone['openid'] != $openid){
                $res = Db::name('wx_fans')->where('openid',$openid)->update($data);
                if($res){
                    return 1;
                }
            }else{
                return '此手机号已经注册，请更换手机号或者联系物业人员';
            }

        }else{
            return 'openid获取失败，请重新打开此页面';
        }
    }

    public function index(){
        $user_id = cookie('user_id');
        $app_id = cookie('app_id');
        $wxInfo = Db::name('wx_info')->where('app_id',$app_id)->find();
        $this->assign('wxInfo',$wxInfo);
        $carousel = Db::name('wy_carousel')->order('time desc')->select();
        $this->assign('carousel',$carousel);
        $notice = Db::name('wy_notice')->where(['user_id'=>$user_id,'cate_id'=>'16','is_show'=>'1'])->order('time desc')->select();
        $this->assign('notice',$notice);

        $nowTime = time();
        $advertWhere['start_time'] = ['ELT',$nowTime];
        $advertWhere['end_time'] = ['EGT',$nowTime];
        $advert = Db::name('advert')->where($advertWhere)->order('addtime desc')->select();
        $this->assign('advert',$advert);
        $wzcx = Db::name('user')->where('id','1')->find();
        $this->assign('wzcx',$wzcx);
        return $this->fetch();
    }


    public function service(){
        $user_id = cookie('user_id');
        $app_id = cookie('app_id');
        $wxInfo = Db::name('wx_info')->where('app_id',$app_id)->find();
        $this->assign('wxInfo',$wxInfo);
        $carousel = Db::name('wy_carousel')->order('time desc')->select();
        $this->assign('carousel',$carousel);
        $notice = Db::name('wy_notice')->where(['user_id'=>$user_id,'cate_id'=>'16','is_show'=>'1'])->order('time desc')->select();
        $this->assign('notice',$notice);

        $wzcx = Db::name('user')->where('id','1')->find();
        $this->assign('wzcx',$wzcx);
        $four = Db::name('four')->where('id','1')->find();
        $this->assign('four',$four);
        return $this->fetch();
    }
    public function service1(){
        $user_id = cookie('user_id');
        $app_id = cookie('app_id');
        $type = input('type');
        $wzcx = Db::name('user')->where('id','1')->find();
        $this->assign('wzcx',$wzcx);
        if($type == 'chexian'){
            $data['openid'] = cookie('openid');
            $data['addtime'] = time();
            $searchRes = Db::name('chexian')->where('openid',$data['openid'])->find();
            if(!$searchRes){
                $res = Db::name('chexian')->insert($data);
            }else{
                $res = Db::name('chexian')->where('openid',$data['openid'])->setInc('num');
            }

            if($res){
                $this->redirect($wzcx['cxbj']);
            }
        }

    }




    public function noticedetail(){
        $id = input('id');
        if(!empty($id)){
            $data = Db::name('wy_notice')->where('id',$id)->find();
            $this->assign('data',$data);
        }
        return view();
    }
    public function guidedetail(){
        $id = input('id');
        if(!empty($id)){
            $data = Db::name('wy_notice')->where('id',$id)->find();
            $this->assign('data',$data);
        }
        return view();
    }
    public function exposuredetail(){
        $id = input('id');
        if(!empty($id)){
            $data = Db::name('wy_notice')->where('id',$id)->find();
            $this->assign('data',$data);
        }
        return view();
    }

    public function baoxiuSave(){
        $data = input();
        $data['openid'] = cookie('openid');
        $data['user_id'] = cookie('user_id');
        $data['time'] = time();
        $files = request()->file('image');
        $imgSrc = [];
        if($files){
            foreach($files as $file){
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->move(ROOT_PATH . 'public' . DS . 'upload');
                if($info){
                    $imgSrc[] = $info->getSaveName();
                }else{
                    // 上传失败获取错误信息
                    echo $file->getError();
                }
            }
        }
        $data['imgsrc'] = implode(',',$imgSrc);
        $res = Db::name('wy_baoxiu')->insert($data);
        if($res){
//            echo '<script>window.location.href = "baoxiudan"</script>';
            $this->redirect('baoxiudan');
        }
    }
//    朋友圈
    public function friendsSvae(){
        $data = input();
        $data['openid'] = cookie('openid');
        $data['user_id'] = cookie('user_id');
        $data['time'] = time();
        $files = request()->file('image');
        $imgSrc = [];
        if($files){
            foreach($files as $file){
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->move(ROOT_PATH . 'public' . DS . 'upload');
                if($info){
                    $imgSrc[] = $info->getSaveName();
                }else{
                    // 上传失败获取错误信息
                    echo $file->getError();
                }
            }
        }
        $data['imgsrc'] = implode(',',$imgSrc);
        $res = Db::name('wy_friend')->insert($data);
        if($res){
//            echo '<script>window.location.href = "baoxiudan"</script>';
            $this->redirect('friend');
        }
    }
    public function friend(){
        $user_id = cookie('user_id');
        $data = Db::table('wy_wy_friend')
            ->alias('f')
            ->join('wy_wx_fans s','f.openid = s.openid')
            ->field('f.*,s.openid,s.nickname,s.remark,s.sex,s.headimgurl')
            ->select();
        $res = '';
        foreach ($data as $k => $v){
            if($v['user_id'] == $user_id){
                $res[] = $data[$k];
            }
        }
//        dump($res);
        $this->assign('data',$res);
        return view();
    }
    public function zan(){
        $id = input('id');
        $openid = cookie('openid');
        $data = Db::name('wy_friend')->where('id',$id)->field('zan,zan_openid')->find();
        if(!empty($data['zan_openid'])){
            $zan_openid = explode(',',$data['zan_openid']);
            if(in_array($openid,$zan_openid)){
                return ['','code'=>0,'msg'=>'已经赞过啦'];
            }
        }else{
            $data['zan'] += 1;
            if(!empty($data['zan_openid'])){
                $data['zan_openid'] .= ','.$openid;
            }else{
                $data['zan_openid'] = $openid;
            }
            $res = Db::name('wy_friend')->where('id',$id)->update($data);
            if($res){
                return ['data'=>$data,'code'=>1,'msg'=>'赞成功'];
            }
        }
    }
    public function huifu(){
        $data['friend_id'] = input('id');
        $data['content'] = input('content');
        $data['js_openid'] = input('js_openid');
        $openid = cookie('openid');
        if($openid == $data['js_openid']){
            return ['code'=>0,'msg'=>'不能给自己评论'];
        }
        $hfz = input('hfz');
        if(!empty($data['content'])){
            $data['hf_openid'] = cookie('openid');
            if(!empty($hfz)){
                $data['hf_openid'] = $hfz;
            }
            $data['time'] = time();
            $res = Db::name('wy_friend_huifu')->insert($data);
            if($res){
                $where['openid'] = cookie('openid');
                $where['user_id'] = cookie('user_id');
                $data = Db::name('wx_fans')->where($where)->field('headimgurl')->find();
                return ['data'=>$data,'code'=>1,'msg'=>'回复成功'];
            }
        }
    }

//    跳蚤市场
    public function marketSvae(){
        $data = input();
        $data['openid'] = cookie('openid');
        $data['user_id'] = cookie('user_id');
        $data['time'] = time();
        $files = request()->file('image');
        $imgSrc = [];
        if($files){
            foreach($files as $file){
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->move(ROOT_PATH . 'public' . DS . 'upload');
                if($info){
                    $imgSrc[] = $info->getSaveName();
                }else{
                    // 上传失败获取错误信息
                    echo $file->getError();
                }
            }
        }
        $data['imgsrc'] = implode(',',$imgSrc);
        $res = Db::name('wy_market')->insert($data);
        if($res){
//            echo '<script>window.location.href = "baoxiudan"</script>';
            $this->redirect('marketlist');
        }
    }
    public function marketlist(){
        $user_id = cookie('user_id');
        $data = Db::table('wy_wy_market')
            ->alias('f')
            ->join('wy_wx_fans s','f.openid = s.openid','left')
            ->join('wy_wx_info b','f.user_id=b.user_id','left')
            ->order('time desc')
            ->field('f.*,s.openid,s.nickname,s.remark,s.sex,s.headimgurl,b.name as wxName')
            ->where('f.user_id',$user_id)
            ->select();
        $res = '';
//        foreach ($data as $k => $v){
//            if($v['user_id'] == $user_id){
//                $res[] = $data[$k];
//            }
//        }
        $this->assign('data',$data);
        return view();
    }
    public function marketZan(){
        $id = input('id');
        $openid = cookie('openid');
        $data = Db::name('wy_market')->where('id',$id)->field('zan,zan_openid')->find();
        if(!empty($data['zan_openid'])){
            $zan_openid = explode(',',$data['zan_openid']);
            if(in_array($openid,$zan_openid)){
                return ['','code'=>0,'msg'=>'已经赞过啦'];
            }
        }else{
            $data['zan'] += 1;
            if(!empty($data['zan_openid'])){
                $data['zan_openid'] .= ','.$openid;
            }else{
                $data['zan_openid'] = $openid;
            }
            $res = Db::name('wy_market')->where('id',$id)->update($data);
            if($res){
                return ['data'=>$data,'code'=>1,'msg'=>'赞成功'];
            }
        }
    }
    public function marketHuifu(){
        $data['market_id'] = input('id');
        $data['content'] = input('content');
        if(!empty($data['content'])){
            $data['hf_openid'] = cookie('openid');
            $data['time'] = time();
            $res = Db::name('wy_market_huifu')->insert($data);
            if($res){
                $where['openid'] = cookie('openid');
                $where['user_id'] = cookie('user_id');
                $data = Db::name('wx_fans')->where($where)->field('headimgurl')->find();
                return ['data'=>$data,'code'=>1,'msg'=>'回复成功'];
            }
        }
    }
    public function marketDetail(){
        $id = input('id');
        $data = Db::table('wy_wy_market')
            ->alias('f')
            ->join('wy_wx_fans s','f.openid = s.openid')
            ->join('wy_wx_info b','f.user_id=b.user_id','left')
            ->where('f.id',$id)
            ->order('time desc')
            ->field('f.*,s.openid,s.nickname,s.sex,s.headimgurl,s.remark,b.name as wxName')
            ->find();
//        dump($data);
        $this->assign('data',$data);
        return view();
    }
    /* *
     *  物流API，快递鸟
     * */
//    物流查询
    public function show_order(){
        $ShipperCode = $this->request->param('value');
        $LogisticCode = $this->request->param('dhText');
        header("Content-type:text/html;charset=utf-8");
        vendor('express.bird');
        $config=array(
            'EBusinessID'=>'1308721',//请到快递鸟官网申请http://kdniao.com/reg
            'AppKey'=>'088eb2ba-2554-4e9e-b53b-accb431a65f3',//请到快递鸟官网申请http://kdniao.com/reg
        );
        $obj=new \express_bird($config);

        $data=array(
            'OrderCode'=>'',//订单编号
            'ShipperCode'=>$ShipperCode,//快递类型
            'LogisticCode'=>$LogisticCode//物流单号
        );
        $res=$obj->getOrderTracesByJson($data);
        $res = json_decode($res);
        return $res;
    }
//    单号自动识别
    public function show_order1(){
        $LogisticCode = $this->request->param('dhText');
        require_once  ROOT_PATH.'simplewind/vendor/express/KdApiOrderDistinguish.php';
        $logisticResult = getOrderTracesByJson($LogisticCode);
        $logisticResult = json_decode($logisticResult);
        return $logisticResult;
    }
//    预约取件
    public function expressyuyue(){
        $data = Db::name('wy_express')->where('user_id',cookie('user_id'))->select();
        $this->assign('data',$data);
        return $this->fetch();
    }

//    报名
    public function signUp(){
        $data['openid'] = cookie('openid');
        $data['user_id'] = cookie('user_id');
        $data['portal_id'] = input('id');
        if(!empty($data['portal_id'])){
            $res = Db::name('wy_signup')->where($data)->find();
            if(!empty($res)){
                self::alert($msg='您已经报名，不可以重复报名');
            }else{
                $insert = Db::name('wy_signup')->insert($data);
                if(!empty($insert)){
                    self::alert($msg='报名成功，请等待活动开启通知');
                }else{
                    self::alert($msg='报名失败，请与活动管理员联系');
                }
            }
        }
    }
    public function alert($msg,$url=''){
        $str = '<script type="text/javascript">';
        $str.="alert('".$msg."');";
        if ($url != "") {
        $str.="window.location.href='{$url}';"; 
        }else {
            $str.="window.history.back();";
        }
       
        echo $str.='</script>';
    }
    public function activedetail(){
        $id = input('id');
        if(!empty($id)){
            $data = Db::name('portal_post')->where('id',$id)->find();
            if(!empty($data)){
                $this->assign('data',$data);
            }
        }
        return view();
    }
    public function reservation(){
        $data = Db::name('wy_reservation')->where('user_id',cookie('user_id'))->order('time desc')->select();
        $this->assign('data',$data);
        return view();
    }

//    美团
//    public function meituan(){
//        $cate_id = input('id');
//        $getAppId = input('app_id');
//        if(!empty($cate_id)){
//            $map['a.cate_id'] = $cate_id;
//        }
//        if(!empty($getAppId)){
//            $where = [
//                'app_id' => $getAppId,
//            ];
//            $info = Db::name('wx_info')->where($where)->find();
//            $map['e.info_id']=array(array('eq',$info['id']),array('eq',0),'OR');
//            $map['a.type'] = 'mei';
//            $mo = Db::table('wy_mei_shang')
//                ->alias('a')
//                ->join('hatProvince b','a.province = b.provinceID','left')
//                ->join('hatCity c','a.city = c.cityID','left')
//                ->join('hatArea d','a.area = d.areaID','left')
//                ->where($map)
//                ->field('a.*,b.province as pName,c.city as cityName,d.area as areaName')
//                ->select();
//        }else{
//            $app_id = cookie('app_id');
//            $where = [
//                'app_id' => $app_id,
//            ];
//            $info = Db::name('wx_info')->where($where)->find();
////            halt($info);
//            $map['e.info_id']=array(array('eq',$info['id']),array('eq',0),'OR');
//            $map['a.type'] = 'mei';
//            $mo = Db::table('wy_mei_shang')
//                ->alias('a')
//                ->join('hatProvince b','a.province = b.provinceID','left')
//                ->join('hatCity c','a.city = c.cityID','left')
//                ->join('hatArea d','a.area = d.areaID','left')
//                ->join('wy_mei_business e','a.add_id = e.id','left')
//                ->where($map)
//                ->field('a.*,b.province as pName,c.city as cityName,d.area as areaName,e.is_shang')
//                ->select();;
//            $mcate = Db::name('mei_cate')->select();
//        }
//
////        halt($mo);
//        $infoAll = Db::name('wx_info')->select();
//        return view('',[
//            'info'=>$info,
//            'infoAll'=>$infoAll,
//            'mo'=>$mo,
//            'mcate'=>$mcate,
//        ]);
//    }
    public function meituan(){
        $cate_id = input('id');
        $app_id = cookie('app_id');
        $info = Db::name('wx_info')->where('app_id',$app_id)->find();
        if(!empty($cate_id)){
            $map['a.cate_id'] = $cate_id;
        }
        $map['a.type'] = 'mei';
        $map['b.area'] = $info['area'];
        $mo = Db::table('wy_mei_shang')
            ->alias('a')
            ->join('wy_mei_business b','a.add_id = b.id','left')
            ->join('wy_hat_province e','b.province = e.provinceID','left')
            ->join('wy_hat_city c','b.city = c.cityID','left')
            ->join('wy_hat_area d','b.area = d.areaID','left')
            ->where($map)
            ->field('a.*,e.province as pName,c.city as cityName,d.area as areaName,b.is_shang')
            ->select();
//        halt($info);
        $mcate = Db::name('mei_cate')->select();
        return view('',[
            'mo'=>$mo,
            'mcate'=>$mcate,
        ]);
    }
    public function meituandetail(){
        $id = input('id');
        if(!empty($id)){
//            $info = Db::name('mei_shang')->where('id',$id)->find();
            $info = Db::table('wy_mei_shang')
                ->alias('a')
                ->join('wy_mei_business b','a.add_id = b.id','left')
                ->join('wy_hat_province e','b.province = e.provinceID','left')
                ->join('wy_hat_city c','b.city = c.cityID','left')
                ->join('wy_hat_area d','b.area = d.areaID','left')
                ->where('a.id',$id)
                ->field('a.*,e.province as pName,c.city as cityName,d.area as areaName,b.is_shang')
                ->find();
            $this->assign('info',$info);
        }
        return view();
    }


    public function jia(){
        $cate_id = input('id');
        $app_id = cookie('app_id');
        $info = Db::name('wx_info')->where('app_id',$app_id)->find();
        if(!empty($cate_id)){
            $map['a.cate_id'] = $cate_id;
        }
        $map['a.type'] = 'jia';
        $map['b.area'] = $info['area'];
        $mo = Db::table('wy_mei_shang')
            ->alias('a')
            ->join('wy_mei_business b','a.add_id = b.id','left')
            ->join('hatProvince e','b.province = e.provinceID','left')
            ->join('hatCity c','b.city = c.cityID','left')
            ->join('hatArea d','b.area = d.areaID','left')
            ->where($map)
            ->field('a.*,e.province as pName,c.city as cityName,d.area as areaName')
            ->select();
        $mcate = Db::name('jia_cate')->where('type','jia')->select();
        return view('',[
            'mo'=>$mo,
            'mcate'=>$mcate,
        ]);
    }
    public function jiadetail(){
        $id = input('id');
        if(!empty($id)){
//            $info = Db::name('mei_shang')->where('id',$id)->find();
            $info = Db::table('wy_mei_shang')
                ->alias('a')
                ->join('wy_mei_business b','a.add_id = b.id','left')
                ->join('hatProvince e','b.province = e.provinceID','left')
                ->join('hatCity c','b.city = c.cityID','left')
                ->join('hatArea d','b.area = d.areaID','left')
                ->where('a.id',$id)
                ->field('a.*,e.province as pName,c.city as cityName,d.area as areaName')
                ->find();
            $this->assign('info',$info);
        }
        return view();
    }

    public function wei(){
        $cate_id = input('id');
        $app_id = cookie('app_id');
        $info = Db::name('wx_info')->where('app_id',$app_id)->find();
        if(!empty($cate_id)){
            $map['a.cate_id'] = $cate_id;
        }
        $map['a.type'] = 'wei';
        $map['b.area'] = $info['area'];
        $mo = Db::table('wy_mei_shang')
            ->alias('a')
            ->join('wy_mei_business b','a.add_id = b.id','left')
            ->join('hatProvince e','b.province = e.provinceID','left')
            ->join('hatCity c','b.city = c.cityID','left')
            ->join('hatArea d','b.area = d.areaID','left')
            ->where($map)
            ->field('a.*,e.province as pName,c.city as cityName,d.area as areaName')
            ->select();
        $mcate = Db::name('jia_cate')->where('type','wei')->select();
        return view('',[
            'mo'=>$mo,
            'mcate'=>$mcate,
        ]);
    }
    public function weidetail(){
        $id = input('id');
        if(!empty($id)){
//            $info = Db::name('mei_shang')->where('id',$id)->find();
            $info = Db::table('wy_mei_shang')
                ->alias('a')
                ->join('wy_mei_business b','a.add_id = b.id','left')
                ->join('hatProvince e','b.province = e.provinceID','left')
                ->join('hatCity c','b.city = c.cityID','left')
                ->join('hatArea d','b.area = d.areaID','left')
                ->where('a.id',$id)
                ->field('a.*,e.province as pName,c.city as cityName,d.area as areaName')
                ->find();
            $this->assign('info',$info);
        }
        return view();
    }

    public function tuo(){
        $cate_id = input('id');
        $app_id = cookie('app_id');
        $info = Db::name('wx_info')->where('app_id',$app_id)->find();

        if(!empty($cate_id)){
            $map['a.cate_id'] = $cate_id;
        }
        $map['a.type'] = 'tuo';
        $map['b.area'] = $info['area'];
        $mo = Db::table('wy_mei_shang')
            ->alias('a')
            ->join('wy_mei_business b','a.add_id = b.id','left')
            ->join('hatProvince e','b.province = e.provinceID','left')
            ->join('hatCity c','b.city = c.cityID','left')
            ->join('hatArea d','b.area = d.areaID','left')
            ->where($map)
            ->field('a.*,e.province as pName,c.city as cityName,d.area as areaName')
            ->select();
        $mcate = Db::name('jia_cate')->where('type','tuo')->select();
        return view('',[
            'mo'=>$mo,
            'mcate'=>$mcate,
        ]);
    }
    public function tuodetail(){
        $id = input('id');
        if(!empty($id)){
//            $info = Db::name('mei_shang')->where('id',$id)->find();
            $info = Db::table('wy_mei_shang')
                ->alias('a')
                ->join('wy_mei_business b','a.add_id = b.id','left')
                ->join('hatProvince e','b.province = e.provinceID','left')
                ->join('hatCity c','b.city = c.cityID','left')
                ->join('hatArea d','b.area = d.areaID','left')
                ->where('a.id',$id)
                ->field('a.*,e.province as pName,c.city as cityName,d.area as areaName')
                ->find();
            $this->assign('info',$info);
        }
        return view();
    }

    public function changename(){
        $remark = input('name');
        $app_id = cookie('app_id');
        $openid = cookie('openid');
        $info = Db::name('wx_info')->where('app_id',$app_id)->find();
        $options = [
            'app_id' => $app_id,         // AppID
            'secret' => $info['app_secret'],     // AppSecret
            'token' => $info['token'],          // Token
            'aes_key' => $info['aes_key'],                 // EncodingAESKey，安全模式下请一定要填写！！！
        ];
        $app = new Application($options);
        $userService = $app->user;
        $wxres = $userService->remark($openid, $remark);
        if($wxres){
            $data['remark'] = $remark;
            $dbres = Db::name('wx_fans')->where('openid',$openid)->update($data);
            if($dbres){
                return 1;
            }else{
                return '添加数据库失败，请联系管理员';
            }
        }else{
            return '微信更新失败，请联系管理员';
        }
    }

    public function me(){
        $app_id = cookie('app_id');
        $openid = cookie('openid');
        $info = Db::name('wx_info')->where('app_id',$app_id)->find();
        return view('',[
            'info' => $info,
        ]);
    }

    public function pay(){
        $where['a.user_id'] = cookie('user_id');
        $where['a.openid'] = cookie('openid');
        $where['a.is_pay'] = 0;
        $list = Db::table('wy_pay')
            ->alias('a')
            ->join('wy_pay_cate b','a.cate_id = b.id')
            ->where($where)
            ->select();
        $where['a.is_pay'] = 1;
        $payed = Db::table('wy_pay')
            ->alias('a')
            ->join('wy_pay_cate b','a.cate_id = b.id')
            ->where($where)
            ->select();
        $config = self::paying();
        return view('',[
            'list'=>$list,
            'payed'=>$payed,
            'config'=>$config,
        ]);
    }
    public function paying(){
        $where['a.user_id'] = cookie('user_id');
        $where['a.openid'] = cookie('openid');
        $where['a.is_pay'] = 0;
        $list = Db::table('wy_pay')
            ->alias('a')
            ->join('wy_pay_cate b','a.cate_id = b.id')
            ->where($where)
            ->select();
        $where['a.is_pay'] = 1;
        $payed = Db::table('wy_pay')
            ->alias('a')
            ->join('wy_pay_cate b','a.cate_id = b.id')
            ->where($where)
            ->select();
        $body = '';
        $total_fee = '';
        $detail = '';
        if(!empty($list)){

            foreach ($list as $k => $v){
                $body .= $list[$k]['name'].',';
                $total_fee += $list[$k]['num'];
                $detail .= $list[$k]['desc'].'；';
            }
        }
        $body = substr($body, 0, -1);
        $detail = substr($detail, 0, -1);
        $total_fee = intval($total_fee * 100);
        $openid = cookie('openid');
        $app_id = cookie('app_id');
        $wxInfo = Db::name('wx_info')->where('app_id',$app_id)->find();
        $options = [
            'app_id' =>$wxInfo['app_id'],         // AppID
            'secret' => $wxInfo['app_secret'],     // AppSecret
            'token' => $wxInfo['token'],          // Token
            'aes_key' =>$wxInfo['aes_key'],
            'payment' => [
                'merchant_id'        => $wxInfo['merchant_id'],
                'key'                => $wxInfo['key'],
                'cert_path'          => ROOT_PATH . 'public/cert.pem', // XXX: 绝对路径！！！！
                'key_path'           => ROOT_PATH . 'public/apiclient_key.pem',      // XXX: 绝对路径！！！！
                'notify_url'         => "http://".$_SERVER['HTTP_HOST']."/portal/wuye/payget/",       // 你也可以在下单时单独设置来想覆盖它
            ],
        ];
        $out_trade_no = md5($openid.time());
        cookie('out_trade_no',$out_trade_no);
        $attributes = [
            'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
            'body'             => $body,
            'detail'           => $body,
            'out_trade_no'     => $out_trade_no,
            'total_fee'        => $total_fee, // 单位：分
//            'notify_url'       => "http://wx.xshun.cn/portal/wuye/payget", // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'openid'           => $openid, // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
            // ...
        ];
        $order = new Order($attributes);
        $app = new Application($options);
        $payment = $app->payment;
        $result = $payment->prepare($order);
        $prepayId = null;
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
        }
        $config = $payment->configForJSSDKPayment($prepayId,false); // 这个方法是取得js里支付所必须的参数用的。
        $config['timeStamp'] = $config['timestamp'];
        $config = json_encode($config);
        return $config;
    }
    public function payQuery(){
        $isPay = input('isPay');

        if($isPay == 'isPay'){
            $con['user_id'] = cookie('user_id');
            $con['openid'] = cookie('openid');
            $con['is_pay'] = 0;
            $isPayEd = Db::table('wy_pay')
                ->where($con)
                ->select();
            foreach ($isPayEd as $k=>$v){
                Db::name('pay')->where(['id'=>$v['id']])->update(['is_pay'=>'1']);
            }
        }
        $where['a.user_id'] = cookie('user_id');
        $where['a.openid'] = cookie('openid');
        $where['a.is_pay'] = 0;
        $starttime = input('starttime');
        $endtime = input('endtime');
        $startTime = empty($starttime) ? 0 : strtotime($starttime);
        $endTime = empty($endtime) ? 0 : strtotime($endtime)+ 86400;
        if (!empty($startTime) && !empty($endTime)) {
            $where['a.time'] = [['>= time', $startTime], ['<= time', $endTime]];
        } else {
            if (!empty($startTime)) {
                $where['a.time'] = ['>= time', $startTime];
            }
            if (!empty($endTime)) {
                $where['a.time'] = ['<= time', $endTime];
            }
        }

        $list = Db::table('wy_pay')
            ->alias('a')
            ->join('wy_pay_cate b','a.cate_id = b.id')
            ->where($where)
            ->select();
        $where['a.is_pay'] = 1;
        $payed = Db::table('wy_pay')
            ->alias('a')
            ->join('wy_pay_cate b','a.cate_id = b.id')
            ->where($where)
            ->select();
        return view('',[
            'list'=>$list,
            'payed'=>$payed,
            'isPay'=>$isPay,
        ]);
    }

    public function payget(){
        $data = input();
        session('payget',$data);
        Log::notice($data);
    }

    public function address(){
        $openid = cookie('openid');
        $dbres = Db::name('wx_fans')->where('openid',$openid)->find();
        return view('',[
            'dbres'=>$dbres,
        ]);
    }
    public function addressSave(){
        $openid = cookie('openid');
        $data = input('post.');
        $dbres = Db::name('wx_fans')->where('openid',$openid)->update($data);
        if($dbres){
            return ['code'=>1,'msg'=>'接收成功','data'=>$data];
        }else{
            return ['code'=>0,'msg'=>'保存失败，请稍后再试','data'=>$data];
        }
    }

    public function rental(){
        $cate = Db::name('rental_can')->select();
        foreach ($cate as $k=>$v){
            switch ($v['cate_id']){
                case '1':
                    $tingshili[$k]['value'] = $cate[$k]['id'];
                    $tingshili[$k]['text'] = $cate[$k]['name'];
                    break;
                case '2':
                    $chaoxiang[$k]['value'] = $cate[$k]['id'];
                    $chaoxiang[$k]['text'] = $cate[$k]['name'];
                    break;
                case '3':
                    $louceng[$k]['value'] = $cate[$k]['id'];
                    $louceng[$k]['text'] = $cate[$k]['name'];
                    break;
                case '4':
                    $leixing[$k]['value'] = $cate[$k]['id'];
                    $leixing[$k]['text'] = $cate[$k]['name'];
                    break;
                case '5':
                    $cqnianxian[$k]['value'] = $cate[$k]['id'];
                    $cqnianxian[$k]['text'] = $cate[$k]['name'];
                    break;
                case '6':
                    $cqleixing[$k]['value'] = $cate[$k]['id'];
                    $cqleixing[$k]['text'] = $cate[$k]['name'];
                    break;
                case '7':
                    $zhuangxiu[$k]['value'] = $cate[$k]['id'];
                    $zhuangxiu[$k]['text'] = $cate[$k]['name'];
                    break;
            }
        }
        $province = Db::table('wy_hat_province')->select();
        $city = Db::table('wy_hat_city')->select();
        $area = Db::table('wy_hat_area')->select();
        $pca = '';
//        foreach ($province as $kP=>$vP){
//            foreach ($city as $kC=>$vC){
//                if($vC['father'] == $vP['provinceID']){
//                    $pca[$kP]['value'] = $vP['provinceID'];
//                    $pca[$kP]['text'] = $vP['province'];
//                    $pca[$kP]['children'][$kC]['value'] = $vC['cityID'];
//                    $pca[$kP]['children'][$kC]['text'] = $vC['city'];
//                    foreach ($area as $kA=>$vA){
//                        if($vA['father'] == $vC['cityID']){
//                            $pca[$kP]['children'][$kC]['value'] = $vC['cityID'];
//                            $pca[$kP]['children'][$kC]['text'] = $vC['city'];
//                            $pca[$kP]['children'][$kC]['children'][$kA]['value'] = $vA['areaID'];
//                            $pca[$kP]['children'][$kC]['children'][$kA]['text'] = $vA['area'];
//                        }
//                    }
//                }
//            }
//        }
//        halt($pca);
//        halt($tingshili);
        return view('',[
            'tingshili'=>json_encode(array_values($tingshili)),
            'chaoxiang'=>json_encode(array_values($chaoxiang)),
            'louceng'=>json_encode(array_values($louceng)),
            'leixing'=>json_encode(array_values($leixing)),
            'cqnianxian'=>json_encode(array_values($cqnianxian)),
            'cqleixing'=>json_encode(array_values($cqleixing)),
            'zhuangxiu'=>json_encode(array_values($zhuangxiu)),
//            'pca'=>json_encode(array_values($pca)),
        ]);
    }
    public function rental1(){
        $cate = Db::name('rental_can')->select();
        foreach ($cate as $k=>$v){
            switch ($v['cate_id']){
                case '1':
                    $tingshili[$k]['value'] = $cate[$k]['id'];
                    $tingshili[$k]['text'] = $cate[$k]['name'];
                    break;
                case '2':
                    $chaoxiang[$k]['value'] = $cate[$k]['id'];
                    $chaoxiang[$k]['text'] = $cate[$k]['name'];
                    break;
                case '3':
                    $louceng[$k]['value'] = $cate[$k]['id'];
                    $louceng[$k]['text'] = $cate[$k]['name'];
                    break;
                case '4':
                    $leixing[$k]['value'] = $cate[$k]['id'];
                    $leixing[$k]['text'] = $cate[$k]['name'];
                    break;
                case '5':
                    $cqnianxian[$k]['value'] = $cate[$k]['id'];
                    $cqnianxian[$k]['text'] = $cate[$k]['name'];
                    break;
                case '6':
                    $cqleixing[$k]['value'] = $cate[$k]['id'];
                    $cqleixing[$k]['text'] = $cate[$k]['name'];
                    break;
                case '7':
                    $zhuangxiu[$k]['value'] = $cate[$k]['id'];
                    $zhuangxiu[$k]['text'] = $cate[$k]['name'];
                    break;
            }
        }
        $province = Db::table('wy_hat_province')->select();
        $city = Db::table('wy_hat_city')->select();
        $area = Db::table('wy_hat_area')->select();
        $pca = '';
//        foreach ($province as $kP=>$vP){
//            foreach ($city as $kC=>$vC){
//                if($vC['father'] == $vP['provinceID']){
//                    $pca[$kP]['value'] = $vP['provinceID'];
//                    $pca[$kP]['text'] = $vP['province'];
//                    $pca[$kP]['children'][$kC]['value'] = $vC['cityID'];
//                    $pca[$kP]['children'][$kC]['text'] = $vC['city'];
//                    foreach ($area as $kA=>$vA){
//                        if($vA['father'] == $vC['cityID']){
//                            $pca[$kP]['children'][$kC]['value'] = $vC['cityID'];
//                            $pca[$kP]['children'][$kC]['text'] = $vC['city'];
//                            $pca[$kP]['children'][$kC]['children'][$kA]['value'] = $vA['areaID'];
//                            $pca[$kP]['children'][$kC]['children'][$kA]['text'] = $vA['area'];
//                        }
//                    }
//                }
//            }
//        }
//        halt($pca);
        return view('',[
            'tingshili'=>json_encode(array_values($tingshili)),
            'chaoxiang'=>json_encode(array_values($chaoxiang)),
            'louceng'=>json_encode(array_values($louceng)),
            'leixing'=>json_encode(array_values($leixing)),
            'cqnianxian'=>json_encode(array_values($cqnianxian)),
            'cqleixing'=>json_encode(array_values($cqleixing)),
            'zhuangxiu'=>json_encode(array_values($zhuangxiu)),
//            'pca'=>json_encode(array_values($pca)),
        ]);
    }
    public function rentalSave(){
        $data = input();
        $data['openid'] = cookie('openid');
        $data['app_id'] = cookie('app_id');
        $data['addtime'] = time();

        $dbres = Db::name('rental')->insert($data);
        $getLastInsID = Db::name('rental')->getLastInsID();
        if($dbres){
            return ['code'=>1,'msg'=>'接收成功','data'=>$getLastInsID];
        }else{
            return ['code'=>0,'msg'=>'保存失败，请稍后再试','data'=>$data];
        }
    }
    public function rentalImg(){
        $files = request()->file('image');
        $imgSrc = [];
        if($files){
            foreach($files as $file){
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->move(ROOT_PATH . 'public' . DS . 'upload');
                if($info){
                    $imgSrc[] = $info->getSaveName();
                }
            }
        }
        $imgsrc = implode(',',$imgSrc);
        return $imgsrc;
//        $res = Db::name('rental')->update(['id'=>$id,'img'=>$imgsrc]);
//        $this->redirect('portal/wuye/lease');
    }

    public function lease(){
        $rental = Db::name('rental')->where('app_id',cookie('app_id'))->select();
        $chuzu = Db::name('rental')->where(['type'=>'chuzu','app_id'=>cookie('app_id')])->select();
        $chushou = Db::name('rental')->where(['type'=>'chushou','app_id'=>cookie('app_id')])->select();
        return view('',[
            'rental'=>$rental,
            'chuzu'=>$chuzu,
            'chushou'=>$chushou,
        ]);
    }

    public function leaseDetail(){
        $id = input('Rid');
//        $res = Db::name('rental')->where('id',$id)->find();
        $res = Db::table('wy_rental')
            ->alias('a')
            ->join('wy_hat_province c','a.province=c.provinceID','left')
            ->join('wy_hat_city d','a.city=d.cityID','left')
            ->join('wy_hat_area e','a.area=e.areaID','left')
            ->where('a.id',$id)
            ->field('a.*,c.province as Pname,c.provinceID,d.city as Cname,d.cityID,e.area as Aname,e.areaID')
            ->find();
        $can = Db::name('rental_can')->select();
        return view('',[
            'res'=>$res,
            'can'=>$can,
            'ROOT_PATH'=>ROOT_PATH,
        ]);
    }

}